<template>
	<div v-show="false" id="myCanvasContent" :style="{
            width: CanvasWidth + 'px',
            height: CanvasHeight + 'px'
        }">
		<canvas id="myCanvas" :width="CanvasWidth" :height="CanvasHeight">您的浏览器不支持 HTML5 canvas 标签。</canvas>
	</div>
</template>

<script>
export default {
	name: 'CanvasPreview',
	props: {
		transAiPicToBase64: Function,
		drawData: {
			default() {
				return {}
			},
		},
		/*  {
          pic: "resource/2020/9/9/0f6nsqcqlhC90tFzrWf7rx00-37eok4vczRzEgWaMfhAsnb00"
          resultRegion: "{"frameInfo":"[{\"prob\":0.700331,\"obj_id\":20001,\"w\":586,\"x\":1300,\"h\":639,\"typeName\":\"人员\",\"y\":29,\"hitUrl\":\"\"}]","imageInfo":{"width":"1920","pic":"resource/2020/9/9/0f6nsqcqlhC90tFzrWf7rx00-37eok4vczRzEgWaMfhAsnb00","height":"1080"}}"
          setTime: "2020-09-09 11:23:05"
        } */
	},
	data() {
		return {
			picObj: {}, // 服务端传来的图片对象
			frameArr: [], // 画框的集合
			CanvasWidth: 1500,
			CanvasHeight: 100,
			zoomIndex: 1, // 默认不缩放，超过区域就缩放
			base64Data: '',
		}
	},
	created() {
		const that = this
		// console.log(that.drawData)
		let resultRegion = that.drawData.resultRegion
		if (resultRegion) {
			try {
				resultRegion = JSON.parse(resultRegion)
				that.picObj = resultRegion.imageInfo
				if (!resultRegion.frameInfo || !that.picObj.width || !that.picObj.height) {
					that.base64Data = resultRegion.imageInfo.pic
					return
				}
				that.frameArr = JSON.parse(resultRegion.frameInfo)
				if (resultRegion.region) {
					that.regionArr = resultRegion.region.split(';').map((n) => {
						return JSON.parse(n)
					})
				}
				that.picObj.width = parseInt(that.picObj.width)
				that.picObj.height = parseInt(that.picObj.height)
				that.$nextTick(() => {
					that.imageLoad()
				})
			} catch (error) {
				this.transAiPicToBase64('')
			}
		}
	},
	methods: {
		// 底图加载完成后
		imageLoad() {
			const that = this
			// 给图片一个合适的容器
			that.zoomIndex = that.CanvasWidth / that.picObj.width
			that.CanvasHeight = that.zoomIndex * that.picObj.height
			that.$nextTick(() => {
				// 在canvas上绘制红框
				that.drawCanvas()
			})
		},
		drawCanvas() {
			const that = this
			//  获取canvas
			that.canvas = document.getElementById('myCanvas')
			//  由于弹窗，确保已获取到
			that.ctx = that.canvas.getContext('2d')
			//  绘制图片 （注意：这里不必把canvas绘制出来，有一个底图image显示就够了）
			let img = new Image() //创建新的图片对象
			img.setAttribute('crossOrigin', 'Anonymous')
			img.src = that.picObj.pic
			img.onload = () => {
				that.ctx.drawImage(img, 0, 0, that.CanvasWidth, that.CanvasHeight)
				that.regionArr &&
					that.regionArr.forEach((n) => {
						that.drawRegion(n)
					})
				// 在canvas上绘制红框
				that.drawRecRed()
			}
		},
		// 画红框
		drawRecRed() {
			const that = this
			/* [{"prob":0.700331,"obj_id":20001,"w":586,"x":1300,"h":639,"typeName":"人员","y":29,"hitUrl":""}] */
			if (that.frameArr.length > 0) {
				let c = document.getElementById('myCanvas')
				let ctx = c.getContext('2d')
				ctx.strokeStyle = 'red'
				ctx.lineWidth = 1
				ctx.font = '20px Georgia'
				ctx.fillStyle = 'red'
				// 循环个红框
				that.frameArr.forEach((item) => {
					let x = (item.x || 0) * that.zoomIndex
					let y = (item.y || 0) * that.zoomIndex
					let w = (item.w || 0) * that.zoomIndex
					let h = (item.h || 0) * that.zoomIndex
					// 文字的起点是左下
					if (item.w && item.h) {
						// 绘制矩形
						ctx.strokeRect(x, y, w, h)
						// c. 文字+图像，文字超过顶，文字放到框下方
						if (y < 25) {
							y = y + h + 20
						}
						// b. 文字+图像，默认文字在框上
						else {
							y -= 5
						}
						// d. 文字+图像，文字超过右侧，文字右对齐
						let textW = (item.typeName || '').length * 20
						let rDistance = that.CanvasWidth - x
						if (rDistance < textW) {
							x = x + w - textW
						}
					} else {
						// a. 只有文字，放到左上角
						x = 10
						y = 25
					}
					// 绘制的文字
					ctx.fillText(item.typeName || '', x, y)
				})
			}
			that.base64Data = that.canvas
				.toDataURL('image/jpg')
				.replace('image/jpg', 'image/octet-stream')
		},
		// 画蓝框区域
		drawRegion(arr) {
			let c = document.getElementById('myCanvas')
			let ctx = c.getContext('2d')
			ctx.strokeStyle = 'blue'
			ctx.lineWidth = 3
			arr.forEach((item, i) => {
				let x = (item.x || 0) * this.zoomIndex
				let y = (item.y || 0) * this.zoomIndex
				if (i == 0) {
					ctx.moveTo(x, y)
				} else {
					ctx.lineTo(x, y)
					if (i == arr.length - 1) {
						ctx.lineTo(arr[0].x * this.zoomIndex, arr[0].y * this.zoomIndex)
					}
				}
			})
			ctx.stroke()
		},
	},
	watch: {
		base64Data: {
			handler: function (val) {
				val && this.transAiPicToBase64(val)
			},
		},
	},
}
</script>

<style scoped>
#myCanvasContent {
	visibility: hidden;
	position: relative;
	background-position: center;
	background-repeat: no-repeat;
	background-size: cover;
	-webkit-user-select: none;
	-moz-user-select: none;
	-ms-user-select: none;
	user-select: none;
}
canvas {
	z-index: 1;
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
}
</style>
